package com.itheima.ydd.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.Result;
import com.itheima.ydd.dto.SysUserDto;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.mapper.SysUserMapper;
import com.itheima.ydd.service.SysRoleService;
import com.itheima.ydd.service.SysUserService;
import com.itheima.ydd.vo.SysUserVo;
import com.itheima.ydd.vo.SysUserVo2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys_user")
@Slf4j
@CrossOrigin
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserMapper sysUserMapper;

    //管理员分页
    @GetMapping("/list")
    public Result page(String login_name, String status, Long phone, int page, int limit) {
        //分页构造器
        Page<SysUser> pageInfo = new Page<>(page, limit);
        Page<SysUserVo> dtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        //模糊查询
        lqw.like(login_name != null, SysUser::getLogin_name, login_name);
        lqw.like(status != null, SysUser::getStatus, status);
        lqw.like(phone != null, SysUser::getPhone, phone);
        lqw.eq(SysUser::getDel_flag, "0");
        //排序
        lqw.orderByDesc(SysUser::getUpdate_date);
        //调用service
        Page<SysUser> page1 = sysUserService.page(pageInfo, lqw);

        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<SysUser> records = page1.getRecords();

        List<SysUserVo> list = records.stream().map(item -> {
            SysUserVo sysUserVo = new SysUserVo();
            String role_ids = item.getRole_id();
            BeanUtils.copyProperties(item, sysUserVo);

            //sys_user表中的role_id带有[""] sys_role表中的id没有此符号 所以匹配不上
            //猜测是否可以手动去除数据库中的sys_user表中的role_id的[""]
            //妈的 不行 手动删除登录就报错

            List<String> rolename = new ArrayList<>();
            List<String> role_id = JSON.parseObject(role_ids, List.class);
            LambdaQueryWrapper<SysRole> lqw1 = new LambdaQueryWrapper<>();
            lqw1.in(SysRole::getId, role_id);
            List<SysRole> sysRoles = sysRoleService.list(lqw1);
            for (SysRole sysRole : sysRoles) {
                rolename.add(sysRole.getName());
            }

/*            role_id = role_id.substring(2, role_id.length() - 2);  //substring去除首尾字符

            SysRole sysRole = sysRoleService.getById(role_id);

            String rolename = sysRole.getName();*/

            sysUserVo.setRolename(rolename);

            return sysUserVo;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);

        return pageInfo != null ? Result.ok("", PageResult.answer(dtoPage.getTotal(), dtoPage.getSize(), dtoPage.getCurrent(), dtoPage.getRecords())) : Result.error("暂无标签数据");

    }

    //管理员详情
    @GetMapping("/rowInfo")
    public Result selectById(String id) {
        log.info("角色详情 id:{}", id);
        SysUser sysUser = sysUserService.getById(id);
        SysUserVo2 sysUserVo = new SysUserVo2();

        sysUser.setPassword(null);
        String role_ids = sysUser.getRole_id();
        List<String> role_id = JSON.parseObject(role_ids, List.class);

        BeanUtils.copyProperties(sysUser, sysUserVo);
        sysUserVo.setRole_id(role_id);
        return Result.ok("", sysUserVo);
    }

    //管理员修改
    @PostMapping("/update")
    public Result update(@RequestBody SysUserVo2 sysUserVo) {
        String password = sysUserVo.getPassword();
        //密码加密
        if (password != null) {
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            sysUserVo.setPassword(password);
        }

        SysUser user = new SysUser();
        BeanUtils.copyProperties(sysUserVo, user);
        user.setRole_id(JSON.toJSONString(sysUserVo.getRole_id()));

        sysUserService.updateById(user);
        return Result.ok("", sysUserVo);
    }

    //管理员删除
    @GetMapping("/del")
    public Result delete(String id) {
        log.info("角色删除 id:{}", id);
        LambdaUpdateWrapper<SysUser> luw = new LambdaUpdateWrapper<>();
        luw.set(SysUser::getDel_flag, "1");
        luw.eq(SysUser::getId, id);
        sysUserService.update(luw);
        return Result.ok("", id);
    }

    //管理员添加
    @PostMapping("/add")
    public Result add(@RequestBody SysUserVo2 sysUserVo) {  //注意接收类型
        log.info("管理员添加 advimg:{}", sysUserVo);
        SysUser user = new SysUser();
        BeanUtils.copyProperties(sysUserVo, user);
        user.setLogin_name(sysUserVo.getLogin_name());
        user.setRole_id(JSON.toJSONString(sysUserVo.getRole_id()));
        user.setDefault_data("1");

        //密码加密
        String password = sysUserVo.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUserVo.setPassword(password);

         int count = sysUserMapper.insert(user);
        return count > 0 ? Result.ok("", sysUserVo) : Result.error("添加成功");

    }


}
